﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace BuyTrainTicket
{
    public partial class QueryLeftTicket : PhoneApplicationPage
    {
        private string username;
        private string password;
        private string sdate;
        private string sfromstation;
        private string stostation;
        public QueryLeftTicket()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue<String>("username", out username);
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            DateTime dateTime = (DateTime)date.Value;
            sdate = dateTime.ToString("yyyy-MM-dd");
            sfromstation = fromstation.Text;
            stostation = tostation.Text;
            if (sdate == null || sfromstation == null || stostation == null)
            {
                MessageBox.Show("请输入日期，始发站和到达站");
                return;
            }

            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=queryleftticket&password=" + password + "&username=" + username + "&date=" + sdate + "&type=queryleftticket&version=8.1");

        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("action=queryleftticket&password=" + password + "&username=" + username + "&date=" + sdate + "&fromstation=" + sfromstation + "&endstation=" + stostation + "&type=queryleftticket&version=8.1");

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    JToken errMsgToken = responseObj.GetValue("errMsg");
                    Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show((string)errMsgToken);
                        });

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                           {
                               MessageBox.Show(response.StatusCode.ToString());
                           });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }

    }
}